package io.plus.common.protocol;

import io.plus.common.packet.metadata.Command;
import io.plus.engine.pulse.PacketMetadata;
import io.plus.server.Status;
import lombok.Data;

@Data
public class Packet extends PacketMetadata {


    /**
     * 包状态码;
     */
    protected Status status;
    /**
     * 消息体;
     */
    protected byte[] body;
    //
    private byte version = 0;
    private byte mask = 0;
    /**
     * 消息命令;
     */
    private Command command;

    public Packet() {
    }

    public Packet(Command command, Status status) {
        this(command, status, null);
    }

    public Packet(Command command, Status status, byte[] body) {

        this.setCommand(command);
        this.setStatus(status);
        this.setBody(body);
    }

    public static byte encodeEncrypt(byte aByte, boolean isEncrypt) {
        if (isEncrypt) {
            return (byte) (aByte | ProtocolConstants.MASK_ENCRYPT);
        } else {
            return aByte;
        }
    }

    public static byte encodeCompress(byte aByte, boolean isCompress) {
        if (isCompress) {
            return (byte) (aByte | ProtocolConstants.MASK_COMPRESS);
        } else {
            return aByte;
        }
    }

    public static byte encodeHasSynSeq(byte aByte, boolean hasSynSeq) {
        if (hasSynSeq) {
            return (byte) (aByte | ProtocolConstants.MASK_HAS_SYNSEQ);
        } else {
            return aByte;
        }
    }

    public static byte encode4ByteLength(byte aByte, boolean is4ByteLength) {
        if (is4ByteLength) {
            return (byte) (aByte | ProtocolConstants.MASK_4_BYTE_LENGTH);
        } else {
            return aByte;
        }
    }

    //
    public static byte decodeEncrypt(byte b) {
        return (byte) (ProtocolConstants.MASK_ENCRYPT & b);
    }

    public static boolean decodeCompress(byte b) {
        return (ProtocolConstants.MASK_COMPRESS & b) != 0;
    }

    public static boolean decodeHasSynSeq(byte b) {
        return (ProtocolConstants.MASK_HAS_SYNSEQ & b) != 0;
    }

    public static boolean decode4ByteLength(byte b) {
        return (ProtocolConstants.MASK_4_BYTE_LENGTH & b) != 0;
    }


}
